<?php
use JMS\Serializer\Tests\Fixtures\Order;
YII::import('dao.bid.*');
YII::import('application.extensions.YiiMailer.YiiMailer');
Yii::import('dao.share.class.InviteEmail');
class PaymentBuyBid extends PaymentProcess {
	
	protected $_bidPackId;
	protected $_earnedbidlogid;
	protected $_paymentsource;
	
	public function save(){

		$db = Yii::app()->db->beginTransaction();
		$bid = new BidDao();
		$bid->customerId=yii::app()->user->id;
	 	$earnedbidlog=new EarnedBidLog();
		try{
			$billingId = $this->billingInfo->saveInfo();
			$paymethod = 'Braintree';

			$bid->getBidModel('cash')->setEnv('parentTransaction');
			$bid->getBidModel('cash')->setEnv('throw');
			$bid->getBidModel('promo')->setEnv('parentTransaction');
			$bid->getBidModel('promo')->setEnv('throw');
			if($this->bidPack instanceof PaymentCouponCode){
				$bid->getBidModel('cash')->setBid($this->bidPack->amount,'CouponCode');
				$bid->getBidModel('promo')->setBid($this->bidPack->bonus,'CouponCode');
				$earnedbidlog->customer_id=yii::app()->user->id;
				$earnedbidlog->amount=$this->bidPack->amount+$this->bidPack->bonus;
				$earnedbidlog->note=$this->bidPack->bidPackTitle." ".($this->bidPack->amount+$this->bidPack->bonus)." Bids";
				$earnedbidlog->value=$this->bidPack->bidPackPrice;
				$earnedbidlog->bid_pack_id=$this->bidPack->bidPackId;
				$earnedbidlog->bid_source_type=1;//buy bid pack
				$earnedbidlog->bid_type=1;//CASH bid
				$earnedbidlog->created=time();
				$earnedbidlog->save();
				
				$couponCodeValidService = new CouponCodeVerificationService();
				$couponCodeValidService->setCouponCode($this->bidPack->couponCode)->lessCouponCode();
				$couponCodeLog = new CouponCodeLog();
				$couponCodeLog->unsetAttributes();
				$couponCodeLog->coupon_code_id = $this->bidPack->bidPackId;
				$couponCodeLog->customer_id = $this->customer->id;
				$couponCodeLog->created = time();
				$couponCodeLog->modified = time();
				$couponCodeLog->object_id = 0;
				$couponCodeLog->real_bids = $this->bidPack->amount;
				$couponCodeLog->promo_bids = $this->bidPack->bonus;
				$couponCodeLog->cost_price = $this->bidPack->bidPackPrice;
				$couponCodeLog->type = 1;
				$couponCodeLog->enable = 1;
				$couponCodeLog->save();
			}else{
				$bid->getBidModel('cash')->setBid($this->bidPack->amount,'BUY_BID');
				$earnedbidlog->customer_id=yii::app()->user->id;
				$earnedbidlog->amount=$this->bidPack->amount;
				$earnedbidlog->note=$this->bidPack->bidPackTitle." ".$this->bidPack->amount." Bids";
				$earnedbidlog->value=$this->bidPack->bidPackPrice;
				$earnedbidlog->bid_pack_id=$this->bidPack->bidPackId;
				$earnedbidlog->bid_source_type=1;//buy bid pack
				$earnedbidlog->bid_type=1;//CASH bid
				$earnedbidlog->created=time();
				$earnedbidlog->save();

				
			}
			
			
			//发送邮件通知用户买了多少BID
			//时间，用户名，BID包种类（价格，数量），过期时间？
			$db->commit();
			$mailer = new YiiMailer();
			$mailer->setView('buy_bids');//调用模板
			$mailer->setData(array('USER_NAME'=>Yii::app()->user->name,'CREDITS_PRICE'=>$this->bidPack->bidPackPrice,'CREDITS_AMOUNT'=>$this->bidPack->amount));//所需数据
			//发送到邮箱
			$customerinfo=Customer::model()->findByPk(Yii::app()->user->id);
			$mailer->AddAddress($customerinfo->email);//目标邮箱
			
			$mailer->Subject = Yii::t('demo', 'Thanks for your BidPack Purchase');//标题
			if(!$mailer->Send()) {
			    echo "Mailer Error: " . $mailer->ErrorInfo;
			}
			
			/**
			 * 受到邀请的用户第一次买bidPack包成功后
			 * 赠送5promo bid
			 */
			$criteria=new CDbCriteria();
			$criteria->addInCondition("bid_pack_id", array(
			     10,11,12,13,14
			));
			$criteria->addCondition("customer_id=".Yii::app()->user->id);
			$earnBid=new EarnedBidLog();
			$bidPackNum=$earnBid->count($criteria);
			if ($bidPackNum==1){
    			$invite=new InviteEmail('register');
    			$invite->email=$customerinfo->email;
    			if ($invite->validate()){
    			    $invite->success();
    			}
			}
			
			
		} catch (Exception $ex){
			$db->rollback();
			$model = new PaymentLog();
			$model->type = "99";
			//$paymentMenthod['paymentType'];
			$model->request = $this->getPaymentCode();
			$model->customer_id = Yii::app()->user->id;
			$model->created = time();
			$model->response = json_encode($ex->getMessage());
			$model->save();
			$this->redirect(Yii::app()->getRequest()->redirect(Yii::app()->baseUrl));
		}		
		return $this;
	}
	
	public function redirect(){

		Yii::app()->session['paymentSuccess'] = true;
		Yii::app()->getRequest()->redirect(Yii::app()->createUrl('dibzees/pdetail/'.$this->_earnedbidlogid.'?paymentsource='.$this->_paymentsource));
	}
	
	public function isPresentee(){
		$customerMark = new CustomerMark();
		$value = $customerMark->getCustomerMrakField($this->customer->id, 'referral_customer_id', 'value');
		return $value;
	}
	
	public function addReferBids(){

		$customerMark = new CustomerMark();
		if($pid = $this->isPresentee()){
			/*
			$isbuybid = $customerMark->getCustomerMrakField($pid, 'bidPack', 'value');
			$islandbuybid = $customerMark->getCustomerMrakField($pid, 'landingBidPack', 'value');
			if($isbuybid || $islandbuybid){
			*/
//				$setting = Setting::model()->find('t.key="refer_setting"');
//				$bids = json_decode($setting->value);
//				$count = Referral::model()->count('presentee_id = '.$this->customer->id.' and referral_customer_id = '.$pid.' and is_gift = 0');

                $info = Referral::model()->find('presentee_id = '.$this->customer->id.' and referral_customer_id = '.$pid.' and is_gift = 0');
				if(!empty($info)){
					$bidService = new BidService();
					$bidService->init()
					->setCustomerId($pid)
					->setBidSourceType(17)
					->setBidType(2)
					->setBonus($info->gift_voucher_bids)
					->setBidPackPrice($info->gift_voucher_bids * ConstService::BID_VALUE_BUY_AUCTION)
					->addBid();
					
					$this->_earnedbidlogid = $bidService->setCustomerId($pid)
					->setBidSourceType(17)
					->setBidType(2)
					->setAmount($info->gift_voucher_bids)
					->setBonus(0)
					->setProductId(0)
					->setBidPackPrice($info->gift_voucher_bids * ConstService::BID_VALUE_BUY_AUCTION)
					->setPaymentMethod(0)
					->setNote("Refer Bid Pack")
					->addEarnedBidLog();
					$bidService->addBidHistory();
					Referral::model()->updateAll(array('is_gift'=>1),'presentee_id = '.$this->customer->id.' and referral_customer_id = '.$pid);
				}
			}
		/*
		}else{
			$info = CustomerMark::model()->findAll('t.key="referral_customer_id" and t.value = '.$this->customer->id);
			$setting = Setting::model()->find('t.key="refer_setting"');
			$bids = json_decode($setting->value);
			foreach ($info as $presenteeid){
				$sql = "
					SELECT
						count(*) as count 
					From 
						customer_mark 
					LEFT JOIN
						referral 
					ON 
						customer_mark.customer_id = referral.presentee_id 
					WHERE
					 	customer_mark.customer_id = ".$presenteeid->customer_id." 
					AND
					 	customer_mark.key='bidPack'
					AND
						referral.is_gift = 0
					";
				$info = Yii::app()->db->createCommand()->queryAll($sql);
				$count = $info['count'];
// 				$count = Referral::model()->count('presentee_id = '.$presenteeid->customer_id.' and referral_customer_id = '.$pid.' and is_gift = 0');
				if($count){
					$bidService = new BidService();
					$bidService->init()
					->setCustomerId($pid)
					->setBidSourceType(17)
					->setBidType(2)
					->setAmount($bids->bids)
					->setBidPackPrice($bids->bids*ConstService::BID_VALUE_BUY_AUCTION)
					->addBid();
						
					$this->_earnedbidlogid = $bidService->setCustomerId($this->customer->id)
					->setBidSourceType(17)
					->setBidType(2)
					->setAmount($bids->bids)
					->setBonus(0)
					->setProductId(0)
					->setBidPackPrice($bids->bids*ConstService::BID_VALUE_BUY_AUCTION)
					->setPaymentMethod(0)
					->setNote("Refer Bid Pack")
					->addEarnedBidLog();
					$bidService->addBidHistory();
					Referral::model()->updateAll(array('is_gift'=>1),'presentee_id = '.$presenteeid->customer_id.' and referral_customer_id = '.$this->customer->id);
				}
			}
		}
		*/
		$customerMark->setCustomerMark($this->customer->id, 'bidPack', 1);
	}
}